//
//  BKUserAccountViewModel.swift
//  微博
//
//  Created by mac on 16/8/11.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit

class BKUserAccountViewModel: NSObject {
    
    static let shareUserAccount :BKUserAccountViewModel = BKUserAccountViewModel()
    
    //用户模型
    var userAccount : BKUserAccount? {
    
        return BKUserAccount.loadUserAccount()
    }
    
    //封装accesstoken,判断逻辑
    var accessToken :String? {
    
        guard let token = userAccount?.access_token else{
        
            return nil
        }
        
        //如果不为空,判断accesstoken的时间是否过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        //降序表示没有过期
        if result == NSComparisonResult.OrderedDescending{
        
            return token
        }else{
        
            return nil
        }
    }
    
    
    //判断是否登录
    var isLogin :Bool {
    
        return accessToken != nil
    }
    
    
    
    //  MARK: --  通过code获取accesstoken
    func requestAccessTokenWithCode (code:String,callBack:(isSuccess:Bool)->()) {
        
        BKNetworkTools.shareTools.requestAccessTokenWithCode(code) { (response, error) -> () in
            
            if error != nil{
                
                print("网络请求失败\(error)")
                return
            }
            
            guard let dic = response as?[String:AnyObject]else{
                
                print("不是一个正确的字典")
                return
            }
            
            let userAccount = BKUserAccount(dic: dic)
            print(userAccount.access_token)
            
            //请求用户基本信息
            self.requestUserInfo(userAccount, callBack: callBack)
        }
    }
    
    //通过accesstoken和uid获取用户的基本信息
    private func requestUserInfo(userAccount:BKUserAccount,callBack:(isSuccess:Bool)->()) {
        
        BKNetworkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in
            
            if error != nil{
                
                print("网络请求失败,\(error)")
                callBack(isSuccess: false)
                return
            }
            
            guard let dic = response as? [String:AnyObject] else{
                
                print("不是一个正确的字典格式")
                callBack(isSuccess: false)
                return
            }
            
            let name = dic["name"]
            let  avatar_large = dic["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //通过重新description方法,来打印用户的所有信息
            print(userAccount)
            
            userAccount.saveUserAccount()
            callBack(isSuccess: true)
        }
        
    }


}
